import avatarUploadTpl from './avatarUpload.html';

function avatarUploadComponent() {
  'ngInject';

  function linkFn(scope, elements, attrs, ctrl) {
    setTimeout(ctrl.initUploader, 700);
  }

  let directive = {
    restrict: 'E',
    replace: true,
    templateUrl: avatarUploadTpl,
    controller: avatarUploadController,
    controllerAs: 'avatarUpload',
    bindToController: {
      imageFile: '=',  // 用于绑定上传成返回的token
      componentId: '@', // 传递组件id
      pickBtnId: '@', // 传递上传图片按钮id
      uploadUrl: '@', // 上传url
    },
    link: linkFn,
  };

  function avatarUploadController($scope, fileUploaderService, $timeout) {
    'ngInject';
    let _this = this;

    // 获得头像src
    this.getAvatarSrc = () => {
      if (this.imageFile && this.imageFile.filePath) {
        let src = `${SERVER_IP}/${this.imageFile.filePath}`;
        return src;
      } else {
        return require('../../../assets/images/' + 'addBt.jpg');
      }
    };

    // 文件加入队列回调函数
    function imgFileQueuedCB(file) {
      let webuploader = this;

      let $selfEle = $(`#${_this.componentId}`);
      webuploader.makeThumb(file, (error, src) => {
        let $img = $selfEle.find('.avatar-img');
        $img.attr('src', src);
      }, 100, 100);
    }

    // 文件上传成功回调函数
    function imgUploadSuccessCB(file, resp) {
      // this指向fileUploader
      let webuploader = this;

      let $selfEle = $(`#${_this.componentId}`);
      let $toastOuter = $selfEle.find('.upload-toast-outer');

      $scope.$apply(() => {
        // 保存返回信息token
        _this.imageFile ? _this.imageFile.id = resp.message : _this.imageFile = {id: resp.message};
      });
      
      // 提示上传成功
      let $toast = $toastOuter.find('.success');
      $toast.show();
      $toast.fadeIn(600);
      setTimeout(() => {
        $toast.fadeOut(600);
      }, 1000);
    }

    // 文件上传失败回调函数
    function imgUploadErrorCB(file, reason) {
      let $selfEle = $(`#${_this.componentId}`);
      $selfEle.find('.error').show();
      $selfEle.find('.retry').show();
    }

    this.initUploader = () => {
      let uploader = fileUploaderService.initUploader({
        auto: true,
        pick: {
          id: `#${_this.pickBtnId}`,
          multiple: false,
        },
        accept: {
          title: 'Images',
          extensions: 'gif,jpg,jpeg,bmp,png',
          mimeTypes: 'image/*'
        },
        server: this.uploadUrl,
      }, imgFileQueuedCB, imgUploadSuccessCB, imgUploadErrorCB);

      uploader.on('error', function(type) {
        if (type == 'Q_EXCEED_NUM_LIMIT') {
          layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
        } else if (type == 'Q_TYPE_DENIED') {
          layer.alert('文件类型错误');
        }
      });
    }
      
  }

  return directive;
}

export default avatarUploadComponent;
